package me.tuyou.jms.spring;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import javax.jms.ConnectionFactory;
import javax.jms.MessageNotWriteableException;

@Configuration
public class ActiveMqApp {

    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL("tcp://localhost:61616");
        return connectionFactory;
    }

    @Bean
    public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
        return jmsTemplate;
    }

    @Bean
    public ActiveMQQueue queue() {
        ActiveMQQueue queue = new ActiveMQQueue("test");
        return queue;
    }

    @Bean
    public DefaultMessageListenerContainer javaConsumer(ConnectionFactory connectionFactory,
                                                        ActiveMQQueue queue,
                                                        MyMessageListener listener) {
        DefaultMessageListenerContainer consumer = new DefaultMessageListenerContainer();
        consumer.setConnectionFactory(connectionFactory);
        consumer.setDestination(queue);
        consumer.setMessageListener(listener);
        return consumer;
    }


    /**
     * web控制台：http://0.0.0.0:8161/
     * 默认账号密码：admin/admin
     * @param args
     * @throws MessageNotWriteableException
     */
    public static void main(String[] args) throws MessageNotWriteableException {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext("me.tuyou.jms.spring");

        JmsTemplate jmsTemplate = applicationContext.getBean(JmsTemplate.class);
        ActiveMQQueue queue = applicationContext.getBean(ActiveMQQueue.class);
        jmsTemplate.send(queue, session -> session.createTextMessage("测试消息"));
        applicationContext.close();
    }
}
